package com.hmall.order.interceptor;


import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    //前置过滤
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户id
        String userId = request.getHeader("authorization");
        // 放入到 ThreadLocal 中
        if (!StringUtils.isEmpty(userId)){
            //将用户id 放入 UserThreadLocal
           UserThreadLocal.set(Long.parseLong(userId));
        }
        // 放行请求
        return true;
    }

    // 后置过滤 响应在发送给客户端之前在进行拦截 可以对响应的内容修改
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 释放本地线程
        UserThreadLocal.remove();
    }
}
